package com.wanxi.education.service.impl;

import com.github.pagehelper.PageHelper;
import com.wanxi.education.mapper.RoleMapper;
import com.wanxi.education.model.pojo.Role;
import com.wanxi.education.model.vo.role.RolePermissionVo;
import com.wanxi.education.model.vo.user.RoleVO;
import com.wanxi.education.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @Author: Kang
 * @Date: 2021/9/27 9:35
 * @Description: 角色业务实现
 * @Version: 1.0
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    /**
     * 通过用户Id查询所属角色
     * @param userId
     * @return
     */
    @Override
    public Set<RoleVO> findByUserId(Long userId) {
        Set<RoleVO> roleVOSet = roleMapper.findByUserId(userId);
        return roleVOSet;
    }

    /**
     *  分页查询所有角色
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public List<RoleVO> findPage(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<RoleVO> roleVOList = roleMapper.findPage();
        return roleVOList;
    }

    @Override
    public Boolean add(RoleVO roleVO) {
        Role role = Role.builder()
                .name(roleVO.getName())
                .description(roleVO.getDescription())
                .createTime(new Date())
                .updateTime(new Date()).build();
        int i = roleMapper.add(role);
        return i == 1 ?true:false;
    }

    /**
     * 通过角色Id查询所属角色基本信息
     * @param roleId
     * @return
     */
    @Override
    public RoleVO findByRoleId(Long roleId) {
        RoleVO roleVO = roleMapper.findByRoleId(roleId);
        return roleVO;
    }

    /**
     *  通过角色Id修改角色基本信息
     * @param roleVO
     * @return
     */
    @Override
    public Boolean updateById(RoleVO roleVO) {
        Role role = Role.builder()
                .id(roleVO.getId())
                .name(roleVO.getName())
                .description(roleVO.getDescription())
                .updateTime(new Date()).build();
        int i = roleMapper.updateById(role);
        return i == 1 ?true:false;
    }

    @Override
    public Boolean deleteByRoleId(Long roleId) {
        int i = roleMapper.deleteByRoleId(roleId);
        return i == 1 ?true:false;
    }

    @Override
    @Transactional
    public void updatePermissionsById(RolePermissionVo rolePermissionVo) {
        roleMapper.deleteRolePermissionById(rolePermissionVo.getId());
        roleMapper.updatePermissionsById(rolePermissionVo);
    }

    @Override
    public List<RoleVO> findAll() {
        return roleMapper.findAll();
    }
}
